import cv2
import mediapipe as mp
import pyautogui
screenWidth, screenHeight = pyautogui.size()

mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(
    static_image_mode=False,
    max_num_hands=2,
    min_detection_confidence=0.75,
    min_tracking_confidence=0.75)


def shibie_wuzhi_zhuangtai(hand_dict):
    finger_list = []
    for finger_poindts in [[2, 3, 4], [6, 7, 8], [10, 11, 12], [14, 15, 16], [18, 19, 20]]:
        x, y, z = finger_poindts
        #
        finger_one = hand_dict[x].y > hand_dict[y].y and hand_dict[y].y > hand_dict[z].y
        finger_list.append(finger_one)
    return finger_list


cap = cv2.VideoCapture(0)
flag=True
currentZ=0
while True:
    ret, frame = cap.read()
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # 因为摄像头是镜像的，所以将摄像头水平翻转
    # 不是镜像的可以不翻转
    frame = cv2.flip(frame, 1)
    results = hands.process(frame)
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
    # if results.multi_handedness:
    #     for hand_label in results.multi_handedness:
    #         print(hand_label)

    if results.multi_hand_landmarks:
        for hand_landmarks in results.multi_hand_landmarks:
            # 识别状态
            hand_dict = {i: v for i, v in enumerate(hand_landmarks.landmark)}
            finger_table = shibie_wuzhi_zhuangtai(hand_dict)
            currentMouseX = int(hand_dict[8].x * screenWidth)
            currentMouseY = int(hand_dict[8].y * screenHeight)
            if flag :
                currentZ=hand_dict[8].z
                if finger_table[1] and sum(finger_table[2:]) == 0:
                    print("只移动鼠标")
                    # currentMouseX, currentMouseY = pyautogui.position()

                    pyautogui.moveTo(x=currentMouseX, y=currentMouseY, duration=0, tween=pyautogui.linear)

                    double_click = 0
                    scrol_click = 0
                    right_click = 0
                    flag=not flag
            else:

                nextZ=hand_dict[8].z
                print((nextZ-currentZ)**2)
                if (nextZ-currentZ)**2>0.001:
                    print("点击")
                    pyautogui.click(x=currentMouseX, y=currentMouseY)
                flag =not flag


                #


            mp_drawing.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
            # break
    cv2.imshow('MediaPipe Hands', frame)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cap.release()

if __name__ == '__main__':
    pass
